package com.springbootvue.blog_upload_image.controller;

import com.springbootvue.blog_upload_image.result.Result;
import com.springbootvue.blog_upload_image.result.ResultInfo;
import com.springbootvue.blog_upload_image.utils.UploadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author Thomas
 * @version 1.0
 * @date 2021/12/8 20:07
 *
 * 用于上传的接口
 */
@RestController
@Api(tags = "上传图片的接口")
@RequestMapping("/upload")
public class UploadHandler {

    @PostMapping("/image")
    @ApiOperation("进行图片上传")
    public Result uploadImage(@RequestParam(value = "file") MultipartFile multipartFile) {
        //调用我们写的上传图片的工具类
        //upload是浏览器浏览的图片路径（http://120.26.196.115:8080/images/30.jpg）
        long size = multipartFile.getSize();
        if(size>5*1024*1024){
            return Result.error().code("404").message("图片超过了5MB!");
        }
        try {
            String upload = UploadUtils.upload(multipartFile);
            return Result.success().codeAndmessage(ResultInfo.SUCCESS).date("src",upload);
        } catch (IOException e) {
            System.out.println(e);
            return Result.error().codeAndmessage(ResultInfo.ERROR).message(e.toString()).date("src","null");
        }
    }
}
